const mongoose = require('mongoose');

const auditLogSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  action: {
    type: String,
    enum: ['create', 'update', 'delete', 'generate', 'login', 'logout'],
    required: true
  },
  resourceType: {
    type: String,
    enum: ['project', 'section', 'form', 'field', 'user'],
    required: true
  },
  resourceId: mongoose.Schema.Types.ObjectId,
  details: {
    before: Object,
    after: Object,
    changes: [String]
  },
  timestamp: {
    type: Date,
    default: Date.now
  },
  ip: String,
  userAgent: String,
  context: {
    projectId: mongoose.Schema.Types.ObjectId,
    sessionId: String,
    requestId: String
  }
}, {
  timestamps: false
});

// 索引
auditLogSchema.index({ userId: 1, timestamp: -1 });
auditLogSchema.index({ resourceType: 1, resourceId: 1, timestamp: -1 });
auditLogSchema.index({ timestamp: -1 });
auditLogSchema.index({ 'context.projectId': 1, timestamp: -1 });
auditLogSchema.index({ 'context.projectId': 1, action: 1, timestamp: -1 });

module.exports = mongoose.model('AuditLog', auditLogSchema);